<template>
  <div class="container">
    <div>
      <el-card class="box-card" style="heigth: 50px">
        <el-page-header @back="cancel" content="编辑页面"> </el-page-header>
      </el-card>
      <el-form ref="form" :model="form" :rules="rulesForm">
        <el-form-item label="上传封面图片">
          <div class="editor-after-div">
            <el-upload
              :class="{ hide: hideUpload }"
              ref="upload"
              action="#"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              list-type="picture-card"
              :limit="1"
              :auto-upload="false"
              :before-upload="handleBeforeUpload"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :file-list="listarr"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <!-- <div class="logo_img">
          <i v-if="isHidden" class="el-icon-picture logo_img_title"></i>
          <img v-else :src="dialogImageUrl" width="100%" height="100%" />
        </div> -->
            <my-cropper
              ref="myCropper"
              @getFile="getFile"
              @upAgain="upAgain"
            ></my-cropper>
          </div>
        </el-form-item>
        <el-form-item label="文章简介" prop="articleExplain">
          <el-input
            type="textarea"
            v-model="form.articleExplain"
            autocomplete="off"
            placeholder="请输入文章简介"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <el-form-item label="文章作者" prop="articleAuthor">
          <el-input
            v-model="form.articleAuthor"
            autocomplete="off"
            placeholder="请输入文章作者"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章类型" prop="articleTypeNum">
          <el-select v-model="form.articleTypeNum" placeholder="请选择文章类型">
            <el-option
              v-for="item in allType"
              :key="item.id"
              :value="item.id"
              :label="item.articleType"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章内容" prop="mdcontent">
          <!-- markdown -->
          <br />
          <div>
            <mavon-editor
              :ishljs="true"
              ref="md"
              @imgAdd="imgAdd"
              @imgDel="imgDel"
              style="height: 100vh; width: 80vw"
              v-model="form.mdContent"
              @change="change"
            ></mavon-editor>
          </div>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button type="primary" @click="confirm('form')">确 定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  getEnbalType,
  deleteArticlePicture,
  deletePicture,
  addPicture,
  getArticleById,
  updateArticlePic,
  updateArticle,
} from "../api/article";
import common from "../utils/common";
import MyCropper from "../components/cropper.vue";

export default {
  components: { MyCropper },

  mounted() {
    this.getTypeList();
    this.getArticleList();
      this.hideUpload = true;

  },
  data() {
    return {
      localhostPath: common.localhostPath,
      form: {
        articleTitle: "",
        articleExplain: "",
        articleAuthor: "",
        articleTypeNum: "",
        articleContent: "", // 转成的html
        mdContent: "", // 输入的markdown
        delivery: false,
      },
      isHidden: false,
      picForm: {
        picPath: "",
      },
      rulesForm: {
        articleTitle: [{ required: true, message: " ", trigger: "blur" }],
        articleExplain: [{ required: true, message: " ", trigger: "blur" }],
        articleAuthor: [{ required: true, message: " ", trigger: "blur" }],
        articleTypeNum: [{ required: true, message: " ", trigger: "blur" }],
        articleContent: [{ required: true, message: " ", trigger: "blur" }],
      },
      allType: [],
      img_file: [],
      dialogImageUrl: "",
      urlForm: {
        oldImgeUrl: "",
      },
      listarr: [],
      //上传一张图片后隐藏上传框
      hideUpload: false,
    };
  },
  methods: {
    getTypeList() {
      getEnbalType().then(({ data }) => {
        data.data.forEach((item) => {
          this.allType.push(item);
        });
      });
    },
    //确定
    confirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var id = localStorage.getItem("articleId");

          if (this.listarr.length > 0) {
            const fileObj = this.listarr[0].file;
            var id = localStorage.getItem("articleId");
            const form1 = new FormData();
            form1.append("imageFile", fileObj);

            updateArticlePic(id, form1).then(({ data }) => {
              console.log(data);
            });

            this.urlForm.oldImgeUrl =
              "/" +
              this.urlForm.oldImgeUrl.split("/")[3] +
              "/" +
              this.urlForm.oldImgeUrl.split("/")[4];

            deleteArticlePicture(this.urlForm).then((data) => {
              console.log(data);
            });

            updateArticle(id, this.form).then(({ data }) => {
              console.log(data);
              this.$message.success(data.msg);
              localStorage.removeItem("articleId");
            });
            this.$router.go(-1);
          }else{
          this.$message.error("封面图不能为空");
            
          }
        } else {
          console.log("error submit!!");
          this.$message.error("请将表单填写完整");
          return false;
        }
      });
    },
    change(value, render) {
      //实时获取转成html的数据
      this.form.articleContent = render;
      this.form.mdContent = value;
    },
    imgDel(pos) {
      delete this.img_file[pos];
      let str = pos[0];
      this.picForm.picPath = "/" + str.split("/")[3] + "/" + str.split("/")[4];
      deletePicture(this.picForm).then((data) => {
        console.log(data);
      });
    },
    // 将图片上传到服务器，返回地址替换到md中
    // 绑定@imgAdd event
    imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append("images", $file);
      addPicture(formdata).then((data) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        // $vm.$img2Url 详情见本页末尾
        var url = this.localhostPath + data.data.data;
        this.$refs.md.$img2Url(pos, url);
      });
    },

    //获取当前文章Id的文章
    getArticleList() {
      var id = localStorage.getItem("articleId");
      getArticleById(id).then(({ data }) => {
        this.form = data.data;
        this.listarr.push({
          url: this.localhostPath + data.data.articleSurface,
        });
        this.urlForm.oldImgeUrl = this.localhostPath + data.data.articleSurface;
      });
    },
    cancel() {
      this.$router.go(-1);
    },

    deleteoic() {
      this.dialogImageUrl = "";
      this.isHidden = true;
    },
    handleBeforeUpload(file) {
      console.log("before");
      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.warning({
          title: "警告",
          message:
            "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
        });
      }
      let size = file.size / 1024 / 1024 / 2;
      if (size > 2) {
        this.$notify.warning({
          title: "警告",
          message: "图片大小必须小于2M",
        });
      }
    },
    handleChange(file, fileList) {
      this.hideUpload = true;
      this.dialogImageUrl = file.url;
      if (fileList.length > 0) {
        this.photoList = [fileList[fileList.length - 1]];
      }
      this.handleCrop(file);
      this.isHidden = false;
    },
    //上传图片触发
    handleCrop(file) {
      this.$nextTick(() => {
        this.$refs.myCropper.open(file.raw || file, 350, 200, 7, 4);
      });
    },
    // 点击弹框重新时触发
    upAgain() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    // 获取裁剪后的图片
    getFile(file) {
      this.$nextTick(() => {
        this.$refs.myCropper.close();
      });
      var url = window.URL.createObjectURL(file);
      this.listarr.push({ name: file.name, url: url, file: file });
    },
    //上传
    handleRemove() {
      this.hideUpload = false;
      this.listarr = [];
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  /* align-items: center; */
  justify-content: center;
}

.clearfix {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 35px;
}
.el-form-item__content {
  display: flex;
  justify-content: flex-end;
}
.dialog-footer {
  float: right;
}
.el-input {
  width: 400px;
}
.el-form {
  margin-top: 30px;
}

.el-icon-plus {
  line-height: 250px;
}

.editor-after-div >>> .el-upload {
  width: 400px;
  height: 250px;
  text-align: center;
  line-height: 250px;
}

.editor-after-div >>> .el-upload-list__item-thumbnail {
  width: 400px;
  height: 250px;
}
.editor-after-div >>> .el-upload-list__item {
  width: 400px;
  height: 250px;
}
</style>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>